package de.gwtprime.client.views.popup;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Receiver;

import de.gwtprime.client.ClientFactory;
import de.gwtprime.client.event.UserSettingsChangedEvent;
import de.gwtprime.shared.requestFactory.User2Proxy;

public class WithdrawCoinsPopup extends PopupPanel {

	private static DepositCoinsPopupUiBinder uiBinder = GWT
			.create(DepositCoinsPopupUiBinder.class);

	interface DepositCoinsPopupUiBinder extends
	UiBinder<Widget, WithdrawCoinsPopup> {
	}

	@UiField TextBox addressBox;
	@UiField TextBox amount;
	@UiField Button sendBtn;

	public WithdrawCoinsPopup(final ClientFactory clientFactory) {
		setWidget(uiBinder.createAndBindUi(this));

		
		setAutoHideEnabled(true);
		setGlassEnabled(true);
		
		addressBox.getElement().setPropertyString("placeholder", "Adresse für die Auszahlung");
		amount.getElement().setPropertyString("placeholder", "Menge an Coins");
		
		sendBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Double amountVal = 0.0;
				try{
					amountVal = Double.valueOf(amount.getText());
				}catch(Exception e){
					Window.alert("Invalid ammount");
					return;
				}

				String address = addressBox.getText();

				clientFactory.getPrimeService().sendCoins(address, amountVal, new AsyncCallback<Boolean>() {

					@Override
					public void onSuccess(Boolean result) {
						Window.alert("Success");
						
						// Reload user with new balance
						clientFactory.getRequestFactory().userRequest().
						findUser2(clientFactory.getUser().getId()).fire(new Receiver<User2Proxy>() {

							@Override
							public void onSuccess(User2Proxy response) {
								
								// Fire event -> This will update the account page
								clientFactory.getEventBus().
								fireEvent(new UserSettingsChangedEvent(response));
								WithdrawCoinsPopup.this.hide();
							}
						});
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Fehler: "+caught.toString());
					}
				});

			}
		});
	}
}
